package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;
    @Autowired
    private EmpExprMapper empExprMapper;

    /**
     * 分页查询
     *
     * @param param
     * @return
     */
    @Override
    public Result pageQuery(EmpQueryParam param) {
        Integer currentPage = param.getPage();
        Integer pageSize = param.getPageSize();
        String name = param.getName();
        Integer gender = param.getGender();
        LocalDate begin = param.getBegin();
        LocalDate end = param.getEnd();
        // 创建分页对象，在调用分页查询方法后，会把分页结果自动封装到分页对象
        Page<Emp> page = Page.of(currentPage, pageSize);
        page.addOrder(OrderItem.desc("update_time"));
        // 封装条件，分页查询方法
        this.lambdaQuery()
                // <if test="name != null && name != ''">and name like concat ('%', #{name}, '%')</if>
                .like(StringUtils.isNotBlank(name), Emp::getName, name)
                // <if test="gender != null">and gender = #{gender}</if>
                .eq(!Objects.isNull(gender), Emp::getGender, gender)
                // <if test="begin != null && end != null">and entry_date between #{begin} and #{end}</if>
                .between(!Objects.isNull(begin) && !Objects.isNull(end), Emp::getEntryDate, begin, end)
                .page(page);
        // 封装结果
        List<Dept> depts = deptService.list();
        // 将List转成Map<部门ID,部门名称>
        Map<Long, String> deptMap = depts.stream()
                .collect(Collectors.toMap(Dept::getId, Dept::getName));
        List<Emp> emps = page.getRecords().stream()
                .peek(emp -> emp.setDeptName(deptMap.get(emp.getDeptId())))
                .toList();
        PageResult<Emp> pageResult = new PageResult<>(page.getTotal(), emps);
        return Result.success(pageResult);
    }

    /**
     * 保存员工及工作经历信息
     *
     * @param emp
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveEmpAndExprList(Emp emp) {
        // 保存员工信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        boolean flag = this.save(emp);
        if(!flag) {
            throw new RuntimeException("保存员工信息失败");
        }
        // 保存工作经历信息
        List<EmpExpr> exprList = emp.getExprList().stream()
                .peek(expr -> expr.setEmpId(emp.getId()))
                .toList();
        flag = empExprService.saveBatch(exprList);
        if(!flag) {
            throw new RuntimeException("保存员工工作经历信息失败");
        }
        return Result.success();
    }

    /**
     * 查询员工及工作经历信息
     *
     * @return
     */
    @Override
    public Result queryEmpAndExprList(Long id) {
        Emp emp = this.getById(id);
        if(!Objects.isNull(emp)){
            emp.setExprList(empExprService.list(
                    new LambdaQueryWrapper<>(EmpExpr.class)
                            .eq(EmpExpr::getEmpId, id)
                    // select * from emp_expr where emp_id = ?
            ));
        }
        return Result.success(emp);
    }

    /**
     * 修改员工及工作经历信息
     *
     * @param emp
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateEmpAndExprList(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        boolean flag = this.updateById(emp);
        if(!flag) {
            throw new RuntimeException("修改员工信息失败");
        }
        //先删除工作经历
        empExprService.remove(new LambdaQueryWrapper<>(EmpExpr.class).eq(EmpExpr::getEmpId, emp.getId()));
        List<EmpExpr> exprList = emp.getExprList().stream()
                .peek(expr -> expr.setEmpId(emp.getId()))
                .toList();
        flag = empExprService.saveBatch(exprList);
        if(!flag) {
            throw new RuntimeException("修改员工工作经历信息失败");
        }
        return Result.success();
    }

    /**
     * 批量删除员工及工作经历信息
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteByIds(List<Integer> ids) {
        // 删除员工基本信息
        boolean flag = this.removeByIds(ids);
        if(!flag) {
            throw new RuntimeException("批量删除员工信息失败");
        }
        // 删除员工工作经历信息
        // remove : 删除返回有影响行数则为true，否则就是false
        try {
            empExprService.remove(new LambdaQueryWrapper<>(EmpExpr.class).in(EmpExpr::getEmpId, ids));
        } catch (Exception e) {
            throw new RuntimeException("批量删除员工工作经历失败");
        }
        // delete : 删除返回影响行数。
        /*int row = empExprMapper.delete(new LambdaQueryWrapper<>(EmpExpr.class).in(EmpExpr::getEmpId, ids));
        if(row < 0) {
            throw new RuntimeException("该员工没有对应的工作经历数据");
        }*/
        return Result.success();
    }
}
